package com.example.day12;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class LockTryLockDemo {
    public static void main(String[] args) {
        //lock锁可以判断是否获取到锁资源
        Lock lock=new ReentrantLock();

        Thread t1=new Thread(()->{
            System.out.println("t1启动。。。。。。。。");
            try {
                //尝试获取锁，等待1s没有获取到，这返回
                if(!lock.tryLock(5, TimeUnit.SECONDS)){
                    System.out.println("等待一秒后，获取锁失败。。");
                }
                System.out.println("t1获取了锁。。");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                //释放锁
                lock.unlock();
            }
        });

        try {
            //main线程
            lock.lock(); //lock锁在main线程上
            System.out.println("main线程获取到了锁。。。");

            t1.start();
            //让t1启动起来
            while (true){
            //业务
            }
        }finally {
            lock.unlock();
        }
    }
}
